package net.huashitong.supervision.appController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sirdc.modules.core.web.JsonBaseController;
import com.sirdc.modules.core.web.model.Message;
import com.sirdc.modules.sys.databean.SysUserDataBean;
import com.sirdc.modules.sys.entity.SysDept;
import com.sirdc.modules.sys.entity.SysLogin;
import com.sirdc.modules.sys.entity.SysUser;
import com.sirdc.modules.sys.filter.SysUserFilter;
import com.sirdc.modules.sys.service.*;
import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;
import com.sirdc.modules.utils.date.DateUtils;
import net.huashitong.supervision.task.dataBean.TaskBackNewBean;
import net.huashitong.supervision.task.dataBean.TaskMainBean;
import net.huashitong.supervision.task.dataBean.TaskSubBean;
import net.huashitong.supervision.task.dataBean.TaskUnitBean;
import net.huashitong.supervision.task.entity.*;
import net.huashitong.supervision.task.filter.*;
import net.huashitong.supervision.task.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

import static net.huashitong.supervision.task.controller.TaskUnitController.splitString;

/**
 * Created with IntelliJ IDEA.
 * User: ling
 * Date: 2019/11/4
 * Time: 19:20
 * To change this template use File | Settings | File Templates.
 * Description:
 */
@Controller
@RequestMapping(value = "/appTaskMain")
public class AppTaskMainController extends JsonBaseController {
    @Autowired
    private SysDeptService sysDeptService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private DeptService deptService;
    @Autowired
    private TaskCategoryService categoryService;
    @Autowired
    private TaskMainService taskMainService;
    @Autowired
    private SysLoginService sysLoginService;
    @Autowired
    private TaskSubService taskSubService;
    @Autowired
    private TaskUserService taskUserService;
    @Autowired
    private TaskLogNewService taskLogNewService;
    @Autowired
    private TaskUnitService taskUnitService;
    @Autowired
    private TaskCategoryService taskCategoryService;
    @Autowired
    private TaskBackNewService taskBackNewService;
    @Autowired
    private CopeToService copeToService;
    @Autowired
    private HastenMessageService hastenMessageService;
    @Autowired
    private CollectService collectService;
    @Autowired
    private TaskCategoryLogService taskCategoryLogService;
    @Autowired
    private MajorBackService majorBackService;
    @Autowired
    private SpecialTaskService specialTaskService;
    @Autowired
    private RedisService redisService;

    @Override
    protected String getView(String s) {
        return null;
    }


    /**
     * 立项
     *
     * @param
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/createTask", method = RequestMethod.POST)
    public Message createTask(@RequestBody AppMainFilter json) {
        TaskMainFilter filter = JSON.parseObject(json.getJson(), TaskMainFilter.class);
        if (StringUtils.isBlank(filter.getTasksubfilterlist())) {
            return coverMessage("500", "立项失败");
        } else {
            JSONArray array = JSON.parseArray(filter.getTasksubfilterlist());
            filter.setTaskSubFilterList(array.toJavaList(TaskSubFilter.class));
        }
        String message = "";
        try {
            message = taskMainService.createTask(filter);
        } catch (Exception e) {
            e.printStackTrace();
            message = e.getMessage();
        }
        if ("保存成功".equals(message)) {
            message = "保存成功";
            return coverMessage("200", message);
        } else {
            return coverMessage("500", message);
        }
    }

    /**
     * 更新待立项
     *
     * @param
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateTask", method = RequestMethod.POST)
    public Message updateTask(@RequestBody AppMainFilter json) {
        TaskMainFilter filter = JSON.parseObject(json.getJson(), TaskMainFilter.class);
        if (StringUtils.isBlank(filter.getTasksubfilterlist())) {
            return coverMessage("500", "立项失败");
        } else {
            JSONArray array = JSON.parseArray(filter.getTasksubfilterlist());
            filter.setTaskSubFilterList(array.toJavaList(TaskSubFilter.class));
        }
        String message = "";
        try {
            message = taskMainService.updateTask(filter);
        } catch (Exception e) {
            e.printStackTrace();
            message = e.getMessage();
        }
        if ("保存成功".equals(message)) {
            message = "保存成功";
            return coverMessage("200", message);
        } else {
            return coverMessage("500", message);
        }
    }

    @Autowired
    private TaskMainDraftService taskMainDraftService;

    /**
     * 保存立项草稿
     *
     * @param taskMainDraft
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/saveTaskDraft", method = RequestMethod.POST)
    public Message saveTaskDraft(TaskMainDraft taskMainDraft) {
        try {
            if (StringUtils.isNotBlank(taskMainDraft.getUserId())) {
                if (StringUtils.isNotBlank(taskMainDraft.getMainName()) || StringUtils.isNotBlank(taskMainDraft.getContent())) {
                    taskMainDraftService.save(taskMainDraft);
                    return coverMessage("200", "已保存至草稿箱");
                } else {
                    return coverMessage("500", "无内容未保存");
                }
            } else {
                return coverMessage("500", "没有用户");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return coverMessage("500", e.getMessage());
        }
    }

    /**
     * 查询当前用户保存过的草稿内容
     *
     * @param draft
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/taskDraftList", method = RequestMethod.POST)
    public Message taskDraftList(TaskMainDraft draft) {
        if (StringUtils.isNotBlank(draft.getUserId())) {
            List<TaskMainDraft> draftList = taskMainDraftService.queryDraftList(draft);
            if (ObjectUtils.isNotBlank(draftList)) {
                return coverMessage("200", "立项草稿列表", draftList);
            } else {
                return coverMessage("500", "无历史草稿");
            }
        } else {
            return coverMessage("500", "没有用户");
        }
    }

    /**
     * 删除草稿箱内容
     *
     * @param draft
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/delDraft", method = RequestMethod.POST)
    public Message delDraft(@RequestBody TaskMainDraft draft) {
        if (StringUtils.isNotBlank(draft.getSysId())) {
            String[] split = draft.getSysId().split(",");
            ArrayList<String> strings = new ArrayList<>(Arrays.asList(split));
            taskMainDraftService.batchDelete(strings);
            return coverMessage("200", "删除成功");
        } else {
            return coverMessage("500", "删除失败");
        }
    }

    /* 天数转日期
     * @param day
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/changeTime", method = RequestMethod.POST)
    public Message changeTime(@RequestBody TaskMainFilter filter) {
        Map<String, String> map = new HashMap<>();
        String day = filter.getDay();
        String time = taskMainService.changeTime(day);
        map.put("time", time);
        return coverMessage("200", "success", map);
    }

    /**
     * 事项类型
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/categoryList", method = RequestMethod.POST)
    public Message categoryList(@RequestBody SysUserDataBean dataBean) {
        try {
            SysUserDataBean userDataBean = sysUserService.getUserDataBeanById(dataBean.getUserId());
            List<TaskCategory> categoryList = new ArrayList<>();
            String floorId = userDataBean.getFloorId();
            if (StringUtils.isNotBlank(floorId)) {
                String[] split = floorId.split(",");
                for (String s : split) {
                    TaskCategory category = categoryService.getById(s);
                    categoryList.add(category);
                }
            }
            if (ObjectUtils.isBlank(categoryList)) {
                categoryList = categoryService.query();
            }
            return coverMessage("200", "success", categoryList);
        } catch (Exception e) {
            e.printStackTrace();
            return coverMessage("500", e.getMessage());
        }
    }

    /**
     * 抄送领导
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/copeToList", method = RequestMethod.POST)
    public Message copeToList() {
      /*  SysUserFilter userFilter = new SysUserFilter();
        userFilter.setRoleId("01");*/
        List<SysLogin> list = sysLoginService.queryCountyleader();
        return coverMessage("200", "success", list);
    }

    /**
     * 审批领导
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/leaderList", method = RequestMethod.POST)
    public Message leaderList(@RequestBody SysUserDataBean dataBean) {
        String userId = dataBean.getUserId();
        SysLogin login = sysLoginService.getById(userId);
        //当前用户上级领导(审批)
        List<SysUser> leaderList = new ArrayList<>();
        List<SysLogin> loginList = sysLoginService.queryLeaderList(login.getDeptId(), login.getRoleId());
        for (SysLogin sysLogin : loginList) {
            SysUser user = sysUserService.getById(sysLogin.getSysId());
            leaderList.add(user);
        }
        if (leaderList.size() <= 0) {
            return coverMessage("500", "无审批上级");
        } else {
            return coverMessage("200", "success", leaderList);
        }
    }

    /**
     * 单位列表
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "deptList", method = RequestMethod.POST)
    public Message deptList() {
        //所有承办单位的二级 单位
        List<SysDept> sysDeptList = deptService.queryByDeptLevel(3);
        return coverMessage("200", "success", sysDeptList);
    }

    @ResponseBody
    @RequestMapping(value = "/mergeList", method = RequestMethod.POST)
    public Message mergeList(@RequestBody SysUserDataBean dataBean) {
        List<TaskCategory> categoryList = categoryService.query();
        Map<String, Object> map = new HashMap<>();
        map.put("categoryList", categoryList);
        SysUserFilter userFilter = new SysUserFilter();
        userFilter.setRoleId("01");
        List<SysLogin> copeToList = sysLoginService.queryUserLoginByRoleDept(userFilter);
        map.put("copeToList", copeToList);

        String userId = dataBean.getUserId();
        SysLogin login = sysLoginService.getById(userId);
        //当前用户上级领导(审批)
        List<SysUser> leaderList = new ArrayList<>();
        List<SysLogin> loginList = sysLoginService.queryLeaderList(login.getDeptId(), login.getRoleId());
        for (SysLogin sysLogin : loginList) {
            SysUser user = sysUserService.getById(sysLogin.getSysId());
            leaderList.add(user);
        }
        map.put("leaderList", leaderList);

        List<SysDept> deptList = deptService.queryByDeptLevel(3);
        map.put("deptList", deptList);


        return coverMessage("200", "success", map);
    }

    @ResponseBody
    @RequestMapping(value = "/deptAndCopyList", method = RequestMethod.POST)
    public Message deptAndCopyList() {
        Map<String, Object> map = new HashMap<>();
        List<SysDept> deptList = deptService.queryByDeptLevel(3);
        map.put("deptList", deptList);
        SysUserFilter userFilter = new SysUserFilter();
        userFilter.setRoleId("01");
        List<SysLogin> copeToList = sysLoginService.queryUserLoginByRoleDept(userFilter);
        map.put("copeToList", copeToList);
        return coverMessage("200", "success", map);
    }

    /**
     * 获取立项的事项类型和领导
     * @param dataBean
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/categoryAndLeaderAndCopyList", method = RequestMethod.POST)
    public Message categoryAndLeaderAndCopyList(@RequestBody SysUserDataBean dataBean) {
        try {
            String userId = dataBean.getUserId();
            Map<String, Object> map = new HashMap<>();
            SysUserDataBean userDataBean = sysUserService.getUserDataBeanById(dataBean.getUserId());
            List<TaskCategory> categoryList = new ArrayList<>();
            String floorId = userDataBean.getFloorId();
            if (StringUtils.isNotBlank(floorId)) {
                String[] split = floorId.split(",");
                for (String s : split) {
                    TaskCategory category = categoryService.getById(s);
                    categoryList.add(category);
                }
            }
            if (ObjectUtils.isBlank(categoryList)) {
                categoryList = categoryService.query();
            }
            map.put("categoryList", categoryList);
            SysLogin login = sysLoginService.getById(userId);
            //当前用户上级领导(审批)
            List<SysUser> leaderList = new ArrayList<>();
            List<SysLogin> loginList = sysLoginService.queryLeaderList(login.getDeptId(), login.getRoleId());
            for (SysLogin sysLogin : loginList) {
                SysUser user = sysUserService.getById(sysLogin.getSysId());
                leaderList.add(user);
            }
            map.put("leaderList", leaderList);
            SysUserFilter userFilter = new SysUserFilter();
            userFilter.setRoleId("01");
            List<SysLogin> copeToList = sysLoginService.queryCountyleader();
            map.put("copeToList", copeToList);
            return coverMessage("200", "success", map);
        } catch (Exception e) {
            e.printStackTrace();
            return coverMessage("500", e.getMessage());
        }
    }


    /**
     * 待办任务
     *
     * @param dataBean
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/dbTaskMain", method = RequestMethod.POST)
    public Message dBTaskMain(@RequestBody SysUserDataBean dataBean) {
        Map<String, Object> map = new HashMap<>();
        TaskMainFilter taskMainFilter = new TaskMainFilter();
        if (StringUtils.isNotBlank(dataBean.getSearch())) {
            taskMainFilter.setMainName(dataBean.getSearch());
        }
        String userId = dataBean.getUserId();
        SysUser user = sysUserService.getById(userId);
        SysLogin sysLogin = sysLoginService.getById(userId);
        SysDept dept = sysDeptService.getById(sysLogin.getDeptId());
        String roleId = sysLogin.getRoleId();
        List<TaskMain> list = new ArrayList<>();
        //查看当前用户待审核的任务
        taskMainFilter.setAuditorId(userId);
        taskMainFilter.setStatus("0");
        list = taskMainService.queryFilter(taskMainFilter);
//        taskMainFilter.setOther("DUCHA");
        if ("/01/".equals(dept.getDeptRelation()) && !dept.getDeptName().startsWith("攻坚")) {
            //不是攻坚办
            taskMainFilter.setAuditorId(null);
            taskMainFilter.setStatus("9");
            taskMainFilter.setInspectionId(dept.getSysId());
            taskMainFilter.setCrucialUser("ZAIBAN");
            //查询攻坚系列
            List<TaskMain> listGjian = taskMainService.queryFilter(taskMainFilter);

            list.addAll(listGjian);
        }
        if ("02".equals(roleId)) {
            //单位领导查看单位所有未完成任务
            taskMainFilter.setAuditorId(null);
            taskMainFilter.setInspectionId(sysLogin.getDeptId());
            taskMainFilter.setStatus("3");
            taskMainFilter.setCrucialUser(null);
            List<TaskMain> list1 = taskMainService.queryFilter(taskMainFilter);
            list.addAll(list1);
            Map<String, TaskMain> mainMap = new HashMap<>();
            for (TaskMain taskMain : list) {
                mainMap.put(taskMain.getSysId(), taskMain);
            }
            list = new ArrayList<TaskMain>(mainMap.values());
        } else {
            //如果都不是.那就只能查看自己的任务
            taskMainFilter.setAuditorId(null);
            taskMainFilter.setCreateUser(userId);
            taskMainFilter.setStatus("3");
            List<TaskMain> list1 = taskMainService.queryFilter(taskMainFilter);
            list.addAll(list1);
        }
        for (TaskMain taskMain : list) {
            if (StringUtils.isNotBlank(taskMain.getCategoryId())) {
                TaskCategory category = taskCategoryService.getById(taskMain.getCategoryId());
                taskMain.setCategoryId(category.getCategory());
                if (StringUtils.isNotBlank(taskMain.getOverdueDept())) {
                    SysDept dept1 = deptService.getById(taskMain.getOverdueDept());
                    taskMain.setOverdueDept(dept1.getDeptName());
                }
            }
        }
        for (TaskMain taskMain : list) {
            taskMain.setTimeLimits(null);
        }
        //对list进行排序
        final String[] regulation = {"3", "0", "2", "4", "1"};
        final List<String> regulationOrder = Arrays.asList(regulation);
        Collections.sort(list, new Comparator<TaskMain>() {
            @Override
            public int compare(TaskMain o1, TaskMain o2) {
                int io1 = regulationOrder.indexOf(o1.getStatus());
                int io2 = regulationOrder.indexOf(o2.getStatus());
                int i = io1 - io2;
                if (i == 0) {
                    //按sysid降序
                    //前面大于后面    结果为大于0
                    if ((o2.getSysId().compareTo(o1.getSysId())) > 0) {
                        return 1;
                    } else {
                        return -1;
                    }
                } else {
                    return io1 - io2;
                }
            }
        });
        map.put("list", list);
        List<Map<String, Object>> mapList = new ArrayList<>();
        CollectFilter collectFilter = new CollectFilter();
        collectFilter.setUserId(userId);
        for (TaskMain taskMain : list) {
            List<CollectEntity> list1 = collectService.getByUserIdAndTaskId(userId, taskMain.getSysId(), "1");
            Map<String, Object> objectMap = new HashMap<>();
            objectMap.put("mian", taskMain);
            if (ObjectUtils.isNotBlank(list1)) {
                objectMap.put("collect", true);
            } else {
                objectMap.put("collect", false);
            }
            mapList.add(objectMap);
        }
        return coverMessage("200", "success", map);
    }

    /**
     * 督查在办
     *
     * @param dataBean
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "zbTaskMain", method = RequestMethod.POST)
    public Message zBTaskMain(@RequestBody SysUserDataBean dataBean) {
        Map<String, Object> map = new HashMap<>();
        TaskMainFilter taskMainFilter = new TaskMainFilter();
        if (StringUtils.isNotBlank(dataBean.getSearch())) {
            taskMainFilter.setMainName(dataBean.getSearch());
        }
        String userId = dataBean.getUserId();
        SysUser user = sysUserService.getById(userId);
        SysLogin sysLogin = sysLoginService.getById(userId);
        SysDept dept = sysDeptService.getById(sysLogin.getDeptId());
        String roleId = sysLogin.getRoleId();
        List<TaskMain> list = new ArrayList<>();
        taskMainFilter.setAuditorId(null);
        taskMainFilter.setCrucialUser(null);
        taskMainFilter.setStatus("4");

        if ("02".equals(roleId)) {
            //单位领导查看单位所有未完成任务
            taskMainFilter.setInspectionId(sysLogin.getDeptId());
            list = taskMainService.getUnDoneFilter(taskMainFilter);

        } else {
            //如果都不是.那就只能查看自己的任务
            taskMainFilter.setCreateUser(userId);
            list = taskMainService.getUnDoneFilter(taskMainFilter);
        }
        for (TaskMain taskMain : list) {
            if (StringUtils.isNotBlank(taskMain.getCategoryId())) {
                TaskCategory category = taskCategoryService.getById(taskMain.getCategoryId());
                taskMain.setCategoryId(category.getCategory());
                if (StringUtils.isNotBlank(taskMain.getOverdueDept())) {
                    SysDept dept1 = deptService.getById(taskMain.getOverdueDept());
                    taskMain.setOverdueDept(dept1.getDeptName());
                }
            }
        }
        //对list进行排序
        final String[] regulation = {"3", "0", "2", "4", "1"};
        final List<String> regulationOrder = Arrays.asList(regulation);
        Collections.sort(list, new Comparator<TaskMain>() {
            @Override
            public int compare(TaskMain o1, TaskMain o2) {
                /*int io1 = regulationOrder.indexOf(o1.getStatus());
                int io2 = regulationOrder.indexOf(o2.getStatus());
                int i = io1 - io2;
                if (i==0){*/
                //按sysid降序
                if ((o2.getSysId().compareTo(o1.getSysId())) > 0) {
                    return 1;
                } else {
                    return -1;
                }
              /*  }else{
                    return io1 - io2;
                }*/
            }
        });
        map.put("list", list);
        return coverMessage("200", "success", map);
    }

    @ResponseBody
    @RequestMapping(value = "wcTaskMain")
    public Message wcTaskMain(@RequestBody SysUserDataBean dataBean) {
        Map<String, Object> map = new HashMap<>();
        TaskMainFilter taskMainFilter = new TaskMainFilter();
        if (StringUtils.isNotBlank(dataBean.getSearch())) {
            taskMainFilter.setMainName(dataBean.getSearch());
        }
        String userId = dataBean.getUserId();
        SysUser user = sysUserService.getById(userId);
        SysLogin sysLogin = sysLoginService.getById(userId);
        String roleId = sysLogin.getRoleId();
        List<TaskMain> list = new ArrayList<>();
        //查看当前用户审核过的已完成任务
        taskMainFilter.setAuditorId(userId);
        taskMainFilter.setStatus("4");
        list = taskMainService.queryFilter(taskMainFilter);
        taskMainFilter.setAuditorId(null);
        if ("02".equals(roleId)) {
            //单位领导查看单位所有完成任务
            taskMainFilter.setInspectionId(sysLogin.getDeptId());
            List<TaskMain> list1 = taskMainService.queryFilter(taskMainFilter);
            list.addAll(list1);
            Map<String, TaskMain> mainMap = new HashMap<>();
            for (TaskMain taskMain : list) {
                mainMap.put(taskMain.getSysId(), taskMain);
            }
            list = new ArrayList<TaskMain>(mainMap.values());
        } else {
            //如果都不是.那就只能查看自己的任务
            taskMainFilter.setCreateUser(userId);
            List<TaskMain> list1 = taskMainService.queryFilter(taskMainFilter);
            list.addAll(list1);
        }
        for (TaskMain taskMain : list) {
            if (StringUtils.isNotBlank(taskMain.getCategoryId())) {
                TaskCategory category = taskCategoryService.getById(taskMain.getCategoryId());
                taskMain.setCategoryId(category.getCategory());
                if (StringUtils.isNotBlank(taskMain.getOverdueDept())) {
                    SysDept dept1 = deptService.getById(taskMain.getOverdueDept());
                    taskMain.setOverdueDept(dept1.getDeptName());
                }
            }
        }
        //对list进行排序
        final String[] regulation = {"3", "0", "2", "4", "1"};
        final List<String> regulationOrder = Arrays.asList(regulation);
        Collections.sort(list, new Comparator<TaskMain>() {
            @Override
            public int compare(TaskMain o1, TaskMain o2) {
             /*   int io1 = regulationOrder.indexOf(o1.getStatus());
                int io2 = regulationOrder.indexOf(o2.getStatus());
                int i = io1 - io2;
                if (i==0){*/
                //按sysid降序
                if ((o2.getSysId().compareTo(o1.getSysId())) > 0) {

                    return 1;
                } else {
                    return -1;
                }
              /*  }else{
                    return io1 - io2;
                }*/
            }
        });
        map.put("list", list);
        return coverMessage("200", "success", map);
    }

    @ResponseBody
    @RequestMapping(value = "/allTaskMain", method = RequestMethod.POST)
    public Message allTaskMain(@RequestBody SysUserDataBean dataBean) {
        Map<String, Object> map = new HashMap<>();
        TaskMainFilter taskMainFilter = new TaskMainFilter();
        if (StringUtils.isNotBlank(dataBean.getSearch())) {
            taskMainFilter.setMainName(dataBean.getSearch());
        }
        String userId = dataBean.getUserId();
        SysLogin sysLogin = sysLoginService.getById(userId);
        String roleId = sysLogin.getRoleId();
        List<TaskMain> list = new ArrayList<>();
        //查看当前用户审核过的已所有任务
        taskMainFilter.setAuditorId(userId);
        list = taskMainService.queryFilter(taskMainFilter);
        taskMainFilter.setAuditorId(null);
        if ("20".equals(roleId)) {
            //管理员
            list = taskMainService.queryFilter(taskMainFilter);
        } else if ("02".equals(roleId)) {
            //单位领导查看单位所有未完成任务
            taskMainFilter.setInspectionId(sysLogin.getDeptId());
            List<TaskMain> list1 = taskMainService.queryFilter(taskMainFilter);
            list.addAll(list1);
            Map<String, TaskMain> mainMap = new HashMap<>();
            for (TaskMain taskMain : list) {
                mainMap.put(taskMain.getSysId(), taskMain);
            }
            list = new ArrayList<TaskMain>(mainMap.values());
        } else {
            //如果都不是.那就只能查看自己的任务
            taskMainFilter.setCreateUser(userId);
            List<TaskMain> list1 = taskMainService.queryFilter(taskMainFilter);
            list.addAll(list1);
        }

        for (TaskMain taskMain : list) {
            if (StringUtils.isNotBlank(taskMain.getCategoryId())) {
                TaskCategory category = taskCategoryService.getById(taskMain.getCategoryId());
                taskMain.setCategoryId(category.getCategory());
                if (StringUtils.isNotBlank(taskMain.getOverdueDept())) {
                    SysDept dept1 = deptService.getById(taskMain.getOverdueDept());
                    taskMain.setOverdueDept(dept1.getDeptName());
                }
            }
        }
        //对list进行排序
        final String[] regulation = {"3", "0", "2", "4", "1"};
        final List<String> regulationOrder = Arrays.asList(regulation);
        Collections.sort(list, new Comparator<TaskMain>() {
            @Override
            public int compare(TaskMain o1, TaskMain o2) {
             /*   int io1 = regulationOrder.indexOf(o1.getStatus());
                int io2 = regulationOrder.indexOf(o2.getStatus());
                int i = io1 - io2;
                if (i==0){*/
                //按sysid降序
                if ((o2.getSysId().compareTo(o1.getSysId())) > 0) {

                    return 1;
                } else {
                    return -1;
                }
               /* }else{
                    return io1 - io2;
                }*/
            }
        });
        map.put("list", list);
        return coverMessage("200", "success", map);
    }

    /**
     * 督查组对单位重大任务的主任务反馈进行判断
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateMainStatus", method = RequestMethod.POST)
    public Message updateMainStatus(@RequestBody TaskMainFilter filter) {
        TaskMain taskMain = taskMainService.getById(filter.getSysId());
        String date = DateUtils.getDate();
        if (ObjectUtils.isBlank(taskMain)) {
            return coverMessage("500", "系统错误，该任务不存在");
        }
        taskMain.setStatus(filter.getStatus());
        String type = taskCategoryService.getById(taskMain.getCategoryId()).getType();
        if ("5".equals(filter.getStatus())) {
            int i = 0;
            //退回重办,督查单位重新变为待办
            taskMain.setOverdueDeptState("0");
            if (StringUtils.isBlank(taskMain.getBackNub())) {
                i = 0;
            } else {
                i++;
            }
            taskMain.setBackNub(i + "");
        } else {
            //办结
            //当前类型任务评分标准
            if (date.compareTo(taskMain.getTimeLimit()) > 0 && StringUtils.isNotBlank(taskMain.getMainResultFile())) {
                //未逾期
                taskMain.setScore(type);
            } else {
                taskMain.setScore("0");
            }
        }
        taskMainService.update(taskMain);
        return coverMessage("200", "处理成功");
    }

    /**
     * 当前重大任务责任单位i每轮情况
     * @param f
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/specialRounds",method = RequestMethod.POST)
    public Message specialRounds(@RequestBody SpecialTaskFilter f){
        if (StringUtils.isNotBlank(f.getTaskMainId())){
            List<SpecialTask> list = specialTaskService.queryFilter(f);
            if (ObjectUtils.isNotBlank(list)){
                return coverMessage("200","success",list);
            }else{
                return coverMessage("500","无记录");
            }
        }else{
            return coverMessage("500","无主任务id");
        }
    }



    /**
     * 督查组单位重大任务的主任务反馈列表
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/majorList", method = RequestMethod.POST)
    public Message majorList(@RequestBody TaskMainFilter filter) {
        TaskMain taskMain = null;
        try {
            taskMain = taskMainService.getById(filter.getSysId());
            List<MajorBack> majorBacks = majorBackService.getByTaskMainId(filter.getSysId());
            if (ObjectUtils.isNotBlank(majorBacks)) {
                return coverMessage("200", "汇总列表", majorBacks);
            } else {
                return coverMessage("500", "无反馈");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return coverMessage("500", e.getMessage());
        }
    }

    /**
     * 办结特殊任务
     *
     * @param major
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/overSpecialTask", method = RequestMethod.POST)
    public Message overSpecialTask(@RequestBody MajorBack major) {
        try {
            MajorBack majorBack = majorBackService.getById(major.getSysId());
            TaskMain taskMain = taskMainService.getById(majorBack.getTaskMainId());
            SpecialTask specialTask = specialTaskService.getById(majorBack.getSpecialId());
            if (ObjectUtils.isBlank(taskMain)) {
                return coverMessage("500", "系统错误,该任务不存在");
            }
            majorBack.setState("4");//办结
            specialTask.setType("4");
            taskMain.setStatus("4");
            majorBack.setSpecialId(major.getSpecialId());
            majorBack.setScore(major.getScore());
            majorBack.setLevelName(major.getLevelName());
            majorBack.setScoreLevelId(major.getScoreLevelId()); //设置该反馈的评价id
            if (majorBack.getDateTime().compareTo(taskMain.getTimeLimit()) >= 0) {
                //反馈时间在时限前
                //未逾期
                specialTask.setScore(major.getScore());
                taskMain.setScore(major.getScore());
            } else {
                specialTask.setScore("0");
                taskMain.setScore("0");
            }
            majorBackService.update(majorBack);
            taskMainService.update(taskMain);
            specialTaskService.update(specialTask);
            return coverMessage("200", "办结成功");
        } catch (Exception e) {
            e.printStackTrace();
            return coverMessage("500", "失败" + e.getMessage());
        }
    }

    /**
     * 督查组对单位重大任务的主任务反馈进行判断
     *
     * @param majorBack
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateMajorState", method = RequestMethod.POST)
    public Message updateMajorState(@RequestBody MajorBack majorBack) {
        MajorBack major = majorBackService.getById(majorBack.getSysId());
        TaskMain taskMain = taskMainService.getById(major.getTaskMainId());
        if (ObjectUtils.isBlank(taskMain)) {
            return coverMessage("500", "系统错误，该任务不存在");
        }
        SpecialTask specialTask = specialTaskService.getById(major.getSpecialId());
//        specialTask.setType();
        taskMain.setStatus(majorBack.getState());
        String type = taskCategoryService.getById(taskMain.getCategoryId()).getType();
        if ("5".equals(major.getState())) {
            major.setState(majorBack.getState());//退回重办5
            int i = 0;
            //退回重办,督查单位重新变为待办
            taskMain.setOverdueDeptState("0");
            if (StringUtils.isBlank(taskMain.getBackNub())) {
                i = 0;
            } else {
                i++;
            }
            taskMain.setBackNub(i + "");
            specialTask.setBackNum(i+"");
            //将改轮任务状态改为退回重办
            specialTask.setType("3");
            specialTask.setStatus("1");//待办
        } else {
            //办结
            major.setState(majorBack.getState());//办结4
            specialTask.setType("4");//办结
            //当前类型任务评分标准
            if (major.getDateTime().compareTo(taskMain.getTimeLimit()) >= 0) {
                //反馈时间在时限前
                //未逾期
                taskMain.setScore(type);
            } else {
                taskMain.setScore("0");
            }
        }
        majorBackService.update(major);
        taskMainService.update(taskMain);
        specialTaskService.update(specialTask);
        return coverMessage("200", "处理成功");
    }


    /**
     * 逾期列表
     *
     * @param dataBean
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/overdueTask", method = RequestMethod.POST)
    public Message overdueTask(@RequestBody SysUserDataBean dataBean) {
        String userId = dataBean.getUserId();
        SysLogin sysLogin = sysLoginService.getById(userId);
        SysDept dept = deptService.getById(sysLogin.getDeptId());
        String search = "";
        if (StringUtils.isNotBlank(dataBean.getSearch())) {
            search = dataBean.getSearch();
        }
        List<TaskUnit> list = new ArrayList<>();
        if ("/01/".equals(dept.getDeptRelation())) {
            //督查单位
            if ("02".equals(sysLogin.getRoleId())) {
                //如果是督查主要领导查询当前单位的所有待办事项
                TaskMainFilter taskMainFilter = new TaskMainFilter();
                if (StringUtils.isNotBlank(search)) {
                    taskMainFilter.setMainName(search);
                }
                taskMainFilter.setInspectionId(dept.getSysId());
                taskMainFilter.setStatus("3");
                taskMainFilter.setOther("DUCHA");
//                List<TaskMain> taskMains3 = taskMainService.queryFilter(taskMainFilter);
                taskMainFilter.setStatus("4");
                taskMainFilter.setOther("");
//                List<TaskMain> taskMains4 = taskMainService.queryFilter(taskMainFilter);
                //在办
                List<TaskMain> unDoneFilter = taskMainService.getUnDoneFilter(taskMainFilter);
                for (TaskMain taskMain : unDoneFilter) {
                    //在办的所有单位任务
                    List<TaskUnit> taskUnits = taskUnitService.getByMainId(taskMain.getSysId());
                    for (TaskUnit taskUnit : taskUnits) {
                        if (taskUnit.getOverdueDay() != null) {
                            list.add(taskUnit);
                        }
                    }
                }
            } else {
                //如果不是只查询自己的待办事项
                TaskMainFilter taskMainFilter = new TaskMainFilter();
                if (StringUtils.isNotBlank(search)) {
                    taskMainFilter.setMainName(search);
                }
                taskMainFilter.setCreateUser(sysLogin.getSysId());
                taskMainFilter.setStatus("3");
                taskMainFilter.setOther("DUCHA");
                List<TaskMain> taskMains3 = taskMainService.queryFilter(taskMainFilter);
                taskMainFilter.setStatus("4");
                taskMainFilter.setOther("");

                List<TaskMain> taskMains4 = taskMainService.queryFilter(taskMainFilter);
                //在办
                List<TaskMain> unDoneFilter = taskMainService.getUnDoneFilter(taskMainFilter);

                for (TaskMain taskMain : unDoneFilter) {
                    //在办的所有单位任务
                    List<TaskUnit> taskUnits = taskUnitService.getByMainId(taskMain.getSysId());
                    for (TaskUnit taskUnit : taskUnits) {
                        if (taskUnit.getOverdueDay() != null) {
                            list.add(taskUnit);
                        }
                    }
                }
            }
        } else {
            //如果不是督查组
            if ("02".equals(sysLogin.getRoleId())) {
                //如果是承办单位领导
                TaskUnitFilter taskUnitFilter = new TaskUnitFilter();
                if (StringUtils.isNotBlank(search)) {
                    taskUnitFilter.setTaskSubName(search);
                    taskUnitFilter.setTaskMainName(search);
                }
                taskUnitFilter.setDeptId(dept.getSysId());

//                List<TaskUnit> unDoneUnit = taskUnitService.getUnDoneUnit(taskUnitFilter);

                taskUnitFilter.setType("4");
//                List<TaskUnit> doneUnit = taskUnitService.queryFilter(taskUnitFilter);
                //单位重大事项
                TaskMainFilter filter = new TaskMainFilter();
                filter.setOverdueDept(dept.getSysId());
                //待办单位重大
//                List<TaskMain> overdueDBDeptMain = taskMainService.queryDBOverdueDept(filter);
//                //单位在办督办任务
//                List<TaskMain> overdueZBDeptMain = taskMainService.queryZBOverdueDept(filter);
//                //单位已完成的重大事项
//                List<TaskMain> overdueWCDeptMain = taskMainService.queryWCOverdueDept(filter);
                //在办
                List<TaskUnit> nowUnit = taskUnitService.getNowUnit(taskUnitFilter);
                for (TaskUnit taskUnit : nowUnit) {
                    if (taskUnit.getOverdueDay() != null) {
                        list.add(taskUnit);
                    }

                }
            } else {
                //只查看自己的任务
                TaskUnitFilter filter = new TaskUnitFilter();
                if (StringUtils.isNotBlank(search)) {
                    filter.setTaskSubName(search);
                    filter.setTaskMainName(search);
                }
                filter.setUserId(userId);
                //待办
//                List<TaskUnit> UnDoneUser = taskUnitService.getUnDoneUser(filter);
//                List<TaskUnit> DoneUser = taskUnitService.getDoneUser(filter);
                //在办
                List<TaskUnit> nowUser = taskUnitService.getNowUser(filter);
                for (TaskUnit taskUnit : nowUser) {
                    if (taskUnit.getOverdueDay() != null) {
                        list.add(taskUnit);
                    }
                }
            }
        }
        String[] regulation = {"2", "0", "5", "3", "4"};
        final List<String> regulationOrder = Arrays.asList(regulation);
        Collections.sort(list, new Comparator<TaskUnit>() {
            @Override
            public int compare(TaskUnit o1, TaskUnit o2) {
               /* int io1 = regulationOrder.indexOf(o1.getType());
                int io2 = regulationOrder.indexOf(o2.getType());
                int i = io1 - io2;
                if (i==0){*/
                //按sysid降序
                if ((o2.getSysId().compareTo(o1.getSysId())) > 0) {

                    return 1;
                } else {
                    return -1;
                }
             /*   }else{
                    return io1 - io2;
                }*/
            }
        });
        return coverMessage("200", "success", list);
    }


    /**
     * 退回重办列表
     *
     * @param dataBean
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/thcbTask", method = RequestMethod.POST)
    public Message thcbTask(@RequestBody SysUserDataBean dataBean) {
        String userId = dataBean.getUserId();
        SysLogin sysLogin = sysLoginService.getById(userId);
        SysDept dept = deptService.getById(sysLogin.getDeptId());

        List<TaskUnit> list = new ArrayList<>();
        if ("/01/".equals(dept.getDeptRelation())) {
            //督查单位
            if ("02".equals(sysLogin.getRoleId())) {
                //如果是督查主要领导查询当前单位的所有待办事项
                TaskMainFilter taskMainFilter = new TaskMainFilter();
                taskMainFilter.setInspectionId(dept.getSysId());
                taskMainFilter.setStatus("3");
                taskMainFilter.setOther("DUCHA");
//                List<TaskMain> taskMains3 = taskMainService.queryFilter(taskMainFilter);
                taskMainFilter.setStatus("4");
                taskMainFilter.setOther("");
//                List<TaskMain> taskMains4 = taskMainService.queryFilter(taskMainFilter);
                //在办
                List<TaskMain> unDoneFilter = taskMainService.getUnDoneFilter(taskMainFilter);
                for (TaskMain taskMain : unDoneFilter) {
                    //在办的所有单位任务
                    List<TaskUnit> taskUnits = taskUnitService.getByMainId(taskMain.getSysId());
                    for (TaskUnit taskUnit : taskUnits) {
                        if ("3".equals(taskUnit.getType())) {
                            list.add(taskUnit);
                        }
                    }
                }
            } else {
                //如果不是只查询自己的待办事项
                TaskMainFilter taskMainFilter = new TaskMainFilter();
                taskMainFilter.setCreateUser(sysLogin.getSysId());
                taskMainFilter.setStatus("3");
                taskMainFilter.setOther("DUCHA");
//                List<TaskMain> taskMains3 = taskMainService.queryFilter(taskMainFilter);
                taskMainFilter.setStatus("4");
                taskMainFilter.setOther("");

//                List<TaskMain> taskMains4 = taskMainService.queryFilter(taskMainFilter);
                //在办
                List<TaskMain> unDoneFilter = taskMainService.getUnDoneFilter(taskMainFilter);

                for (TaskMain taskMain : unDoneFilter) {
                    //在办的所有单位任务
                    List<TaskUnit> taskUnits = taskUnitService.getByMainId(taskMain.getSysId());
                    for (TaskUnit taskUnit : taskUnits) {
                        if ("3".equals(taskUnit.getType())) {
                            list.add(taskUnit);
                        }
                    }
                }
            }
        } else {
            //如果不是督查组
            if ("02".equals(sysLogin.getRoleId())) {
                //如果是承办单位领导
                TaskUnitFilter taskUnitFilter = new TaskUnitFilter();
                taskUnitFilter.setDeptId(dept.getSysId());

//                List<TaskUnit> unDoneUnit = taskUnitService.getUnDoneUnit(taskUnitFilter);

                taskUnitFilter.setType("4");
                List<TaskUnit> doneUnit = taskUnitService.queryFilter(taskUnitFilter);
                //单位重大事项
                TaskMainFilter filter = new TaskMainFilter();
                filter.setOverdueDept(dept.getSysId());
                //待办单位重大
//                List<TaskMain> overdueDBDeptMain = taskMainService.queryDBOverdueDept(filter);
//                //单位在办督办任务
//                List<TaskMain> overdueZBDeptMain = taskMainService.queryZBOverdueDept(filter);
//                //单位已完成的重大事项
//                List<TaskMain> overdueWCDeptMain = taskMainService.queryWCOverdueDept(filter);
                //在办
                List<TaskUnit> nowUnit = taskUnitService.getNowUnit(taskUnitFilter);
                for (TaskUnit taskUnit : nowUnit) {
                    if ("3".equals(taskUnit.getType())) {
                        list.add(taskUnit);
                    }

                }

            } else {
                //只查看自己的任务
                TaskUnitFilter filter = new TaskUnitFilter();
                filter.setUserId(userId);
                //待办
//                List<TaskUnit> UnDoneUser = taskUnitService.getUnDoneUser(filter);
//                List<TaskUnit> DoneUser = taskUnitService.getDoneUser(filter);
                //在办
                List<TaskUnit> nowUser = taskUnitService.getNowUser(filter);
                for (TaskUnit taskUnit : nowUser) {
                    if ("3".equals(taskUnit.getType())) {
                        list.add(taskUnit);
                    }
                }
            }
        }
        String[] regulation = {"2", "0", "5", "3", "4"};
        final List<String> regulationOrder = Arrays.asList(regulation);
        Collections.sort(list, new Comparator<TaskUnit>() {
            @Override
            public int compare(TaskUnit o1, TaskUnit o2) {
              /*  int io1 = regulationOrder.indexOf(o1.getType());
                int io2 = regulationOrder.indexOf(o2.getType());
                int i = io1 - io2;
                if (i==0){*/
                //按sysid降序
                if ((o2.getSysId().compareTo(o1.getSysId())) > 0) {

                    return 1;
                } else {
                    return -1;
                }
               /* }else{
                    return io1 - io2;
                }*/
            }
        });
        return coverMessage("200", "success", list);

    }

    /**
     * 催办记录
     *
     * @param dataBean
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/cbMessage", method = RequestMethod.POST)
    public Message cbMessage(@RequestBody SysUserDataBean dataBean) {
        String userId = dataBean.getUserId();
        HastenMessageFilter hastenMessageFilter = new HastenMessageFilter();
        hastenMessageFilter.setCreateId(userId);
//        hastenMessageFilter.setStatus("0");
        List<HastenMessage> list = hastenMessageService.queryFilter(hastenMessageFilter);
        return coverMessage("200", "success", list);
    }


    /**
     * 主任务二级页面数据。单位任务；列表
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/taskUnitList", method = RequestMethod.POST)
    public Message taskUnitList(@RequestBody TaskUnitFilter filter) {
        if (StringUtils.isNotBlank(filter.getSearch())) {
            String search = filter.getSearch();
            filter.setTaskSubName(search);
        }
        //主任务id
        String taskMainId = filter.getTaskMainId();
        List<TaskUnit> taskUnitList = taskUnitService.queryTaskUnit(filter);
        return coverMessage("200", "success", taskUnitList);
    }


    /**
     * \
     * 催办的人
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/urgeModel", method = RequestMethod.POST)
    public Message urgeModel(@RequestBody TaskUnitFilter filter) {
        String taskUnitId = filter.getSysId();
        //新建一个set集合存放要返回的用户信息集合
        Set<SysUser> sysUsers = new HashSet<>();
//        List<SysUser> userList =new ArrayList<>();
        //当前催办的单位任务
        TaskUnit taskUnit = taskUnitService.getById(taskUnitId);
        //当前任务承办单位
        SysDept dept = deptService.getById(taskUnit.getDeptId());
        //根据当前单位任务id查询是否有批转
        List<TaskUser> taskUserList = taskUserService.getByTaskUnitId(taskUnitId);
        if (ObjectUtils.isBlank(taskUserList)) {
            //没有批转过,查询当前单位主要领导的信息
            SysUserFilter userFilter = new SysUserFilter();
            userFilter.setRoleId("02");
            userFilter.setDeptId(dept.getSysId());
            List<SysLogin> loginList = sysLoginService.queryUserLoginByRoleDept(userFilter);
            for (SysLogin sysLogin : loginList) {
                SysUser user = sysUserService.getById(sysLogin.getSysId());
                sysUsers.add(user);
            }
        } else {
            //主要领导已经批转给单位人员。查询当前批转给当前单位人员的任务
            for (TaskUser taskUser : taskUserList) {
                //当前单位人员任务的userid
                SysLogin login = sysLoginService.getById(taskUser.getUnitUserId());
                //判断当前用户是否是分管
                if ("03".equals(login.getRoleId())) {
                    //如果是分管，判断他是否批转过这个单位任务
                    //根据人员任务创建的 id 判断分管是否有批转下去
                    List<TaskUser> taskUsers = taskUserService.getByCreateUserAndTaskUnitId(taskUnitId, login.getSysId());
                    if (ObjectUtils.isBlank(taskUsers)) {
                        //没有批转过就返回当前分管的信息
                        SysUser fgUser = sysUserService.getById(login.getSysId());
                        sysUsers.add(fgUser);
                    } else {
                        //如果批转过就添加批转了的人员的信息
                        for (TaskUser user : taskUsers) {
                            SysUser jbUser = sysUserService.getById(user.getUnitUserId());
                            sysUsers.add(jbUser);
                        }
                    }
                } else {
                    //就是经办人员
                    SysUser sysUser = sysUserService.getById(taskUser.getUnitUserId());
                    sysUsers.add(sysUser);
                }
            }
        }
        if (ObjectUtils.isBlank(sysUsers)) {
            return coverMessage("500");
        } else {
            return coverMessage("200", "success", sysUsers);
        }
    }

    /**
     * 保存催办信息
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/saveHasten", method = RequestMethod.POST)
    public Message saveHasten(@RequestBody HastenMessageFilter filter) {
        if (StringUtils.isBlank(filter.getUserlist())) {
            return coverMessage("500", "保存失败");
        } else {
            JSONArray array = JSON.parseArray(filter.getUserlist());
            filter.setUserList(array.toJavaList(SysUser.class));
        }
        String s = hastenMessageService.saveHasten(filter);
        if ("200".equals(s)) {
            return coverMessage("200", "保存成功");
        } else {
            return coverMessage("500", "保存失败");
        }
    }

    /**
     * 单位任务详情数据
     *
     * @param taskUnitFilter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/taskUnitDetail", method = RequestMethod.POST)
    public Message taskUnitDetail(@RequestBody TaskUnitFilter taskUnitFilter) {
        Map<String, Object> map = new HashMap<>();
        //单位任务id
        String taskUnitId = taskUnitFilter.getSysId();
        TaskUnit taskUnit = taskUnitService.getById(taskUnitId);
        TaskMain taskMain = taskMainService.getById(taskUnit.getTaskMainId());
        TaskSub taskSub = taskSubService.getById(taskUnit.getTaskSubId());
        String taskSubName = taskUnit.getTaskSubName();
        List<TaskLogNew> logNewList = taskLogNewService.getByUnitId(taskUnitId);
        //查看当前任务反馈给我的信
        List<TaskBackNew> taskBackNewList = new ArrayList<>();
//        List<TaskBackNew> taskBackNewList = taskBackNewService.getByTaskUnitIdAndRecipientId(taskUnitId, userId);
        //督查角色查看当前单位主要领导 的反馈信息
        SysDept dept = deptService.getById(taskUnit.getDeptId());
        SysUserFilter userFilter = new SysUserFilter();
        userFilter.setDeptId(dept.getSysId());
        userFilter.setRoleId("02");
        List<SysLogin> loginList = sysLoginService.queryUserLoginByRoleDept(userFilter);
        for (SysLogin sysLogin : loginList) {
            List<TaskBackNew> taskBackNews = taskBackNewService.getByTaskUnitIdAndSenderId(taskUnit.getSysId(), sysLogin.getSysId());
            taskBackNewList.addAll(taskBackNews);
        }
        //当前单位任务领导是否有批示信息
        //查询当前任务是否有抄送,当前主任务的抄送领导
        List<HastenMessage> leaderMessages = new ArrayList<>();
        List<CopeTo> copeTos = copeToService.getByTaskMainId(taskMain.getSysId());
        if (ObjectUtils.isNotBlank(copeTos)) {
            for (CopeTo copeTo : copeTos) {
                String leaderId = copeTo.getLeaderId();
                //查看当前领导对当前单位任务有没有批示信息
                HastenMessageFilter filter = new HastenMessageFilter();
                filter.setCreateId(leaderId);
                filter.setTaskUnitId(taskUnitId);
                List<HastenMessage> messages = hastenMessageService.queryFilter(filter);
                if (ObjectUtils.isNotBlank(messages)) {
                    leaderMessages.addAll(messages);
                }
            }
        }
        //历史轮次
        List<Map<String, Object>> oldTask = new ArrayList<>();
        oldTask = taskUnitService.getByOldTaskUnit(taskUnit.getTaskSubId(), taskUnit.getDeptId());
        if (ObjectUtils.isBlank(oldTask)) {
            oldTask = new ArrayList<>();
        }
        System.out.println(oldTask.toArray());
        map.put("oldTask", oldTask);
        //抄送领导给当前单位的批示信息
        map.put("leaderMessages", leaderMessages);
        //单位任务实体类
        map.put("taskUnit", taskUnit);
        //反馈集合
        map.put("taskBackNewList", taskBackNewList);
        map.put("taskSubName", taskSubName);
        //子任务
        map.put("taskSub", taskSub);
        //主任务
        map.put("taskMain", taskMain);
        //流程
        map.put("logNewList", logNewList);
        return coverMessage("200", "success", map);

    }
/*

    @ResponseBody
    @RequestMapping(value = "/leaderMessage")
    public Message leaderMessage(@RequestBody SysUserDataBean dataBean){
        SysUserFilter userFilter = new SysUserFilter();
        userFilter.setRoleId("01");
        //查询当前用户的所有单位任务
        taskUnitService.
        List<SysLogin> loginList = sysLoginService.queryUserLoginByRoleDept(userFilter);
        for (SysLogin sysLogin : loginList) {
            //领导用户id
            String sysId = sysLogin.getSysId();
            //查询所有的领导创建的批示信息
            HastenMessageFilter messageFilter = new HastenMessageFilter();
            messageFilter.setCreateId(sysId);
            //批示件信息列表
            List<HastenMessage> messageList = hastenMessageService.queryFilter(messageFilter);

        }
    }
*/


    /**
     * 县直排名
     *
     * @param dataBean
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/xianzhiTableScore")
    public Message tableScore(@RequestBody SysUserDataBean dataBean) {
        //如果是县直单位取出说有县直单位
        List<Map<String, Object>> tableList = new ArrayList<>();
        DecimalFormat df = new DecimalFormat("#.00");
        List<SysDept> list = deptService.queryDeptList("/02/202/");
        for (SysDept sysDept : list) {
            //根据当前单位查询该单位的任务
            Map<String, Object> map = new HashMap<>();
            TaskUnitFilter taskUnitFilter = new TaskUnitFilter();
            taskUnitFilter.setCategoryId("20191022100000000002");
            taskUnitFilter.setDeptId(sysDept.getSysId());
            //任务数
            int allSize = taskUnitService.queryByCategory(taskUnitFilter).size();
            taskUnitFilter.setType("3");
            //重办数
            int cbSize = taskUnitService.queryByCategory(taskUnitFilter).size();
            //已完成数
            taskUnitFilter.setType("4");
            List<TaskUnitBean> taskUnitList = taskUnitService.queryByCategory(taskUnitFilter);
            int ywcSize = taskUnitList.size();
            //得分
            int scores = 0;
            for (TaskUnitBean taskUnit : taskUnitList) {
                if (StringUtils.isNotBlank(taskUnit.getScore())) {
                    int score = Integer.parseInt(taskUnit.getScore());
                    scores += score;
                }
            }
            //完成率
            double d = 0;
            if (ywcSize > 0) {
                String format = df.format((float) ywcSize / (float) allSize * 100);
                d = Double.parseDouble(format);
            }

            map.put("scores", scores);//单位总分
            map.put("wcl", d);
            map.put("deptName", sysDept.getDeptName());
            tableList.add(map);
        }
        if (tableList != null && tableList.size() > 1) {
            Collections.sort(tableList, new Comparator<Map<String, Object>>() {
                @Override
                public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                    Double o1Value = Double.valueOf(o1.get("wcl").toString());
                    Double o2Value = Double.valueOf(o2.get("wcl").toString());
                    return o2Value.compareTo(o1Value);
                }
            });
        }
        for (int i = 0; i < tableList.size(); i++) {
            Map<String, Object> map = tableList.get(i);
            map.put("pm", i + 1);
        }
        return coverMessage("200", "success", tableList);
    }


    /**
     * 乡镇排名
     *
     * @param dataBean
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/xiangzhenTableScore")
    public Message townTableScore(@RequestBody SysUserDataBean dataBean) {
        //如果是县直单位取出说有县直单位
        List<Map<String, Object>> tableList = new ArrayList<>();
        DecimalFormat df = new DecimalFormat("#.00");
        List<SysDept> list = deptService.queryDeptList("/02/201/");
        for (SysDept sysDept : list) {
            //根据当前单位查询该单位的任务
            Map<String, Object> map = new HashMap<>();
            TaskUnitFilter taskUnitFilter = new TaskUnitFilter();
            taskUnitFilter.setCategoryId("20191022100000000002");
            taskUnitFilter.setDeptId(sysDept.getSysId());
            //任务数
            int allSize = taskUnitService.queryByCategory(taskUnitFilter).size();
            taskUnitFilter.setType("3");
            //重办数
            int cbSize = taskUnitService.queryByCategory(taskUnitFilter).size();
            //已完成数
            taskUnitFilter.setType("4");
            List<TaskUnitBean> taskUnitList = taskUnitService.queryByCategory(taskUnitFilter);
            int ywcSize = taskUnitList.size();
            //得分
            int scores = 0;
            for (TaskUnitBean taskUnit : taskUnitList) {
                if (StringUtils.isNotBlank(taskUnit.getScore())) {
                    int score = Integer.parseInt(taskUnit.getScore());
                    scores += score;
                }
            }
            //完成率
            double d = 0;
            if (ywcSize > 0) {
                String format = df.format((float) ywcSize / (float) allSize * 100);
                d = Double.parseDouble(format);
            }

            map.put("scores", scores);//单位总分
            map.put("wcl", d);
            map.put("deptName", sysDept.getDeptName());
            tableList.add(map);
        }
        if (tableList != null && tableList.size() > 1) {
            Collections.sort(tableList, new Comparator<Map<String, Object>>() {
                @Override
                public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                    Double o1Value = Double.valueOf(o1.get("wcl").toString());
                    Double o2Value = Double.valueOf(o2.get("wcl").toString());
                    return o2Value.compareTo(o1Value);
                }
            });
        }
        for (int i = 0; i < tableList.size(); i++) {
            Map<String, Object> map = tableList.get(i);
            map.put("pm", i + 1);
        }
        return coverMessage("200", "success", tableList);
    }


    /**
     * 督查处理反馈结果
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateBackNew", method = RequestMethod.POST)
    public Message updateBackNew(@RequestBody TaskBackNewFilter backNewFilter) {
        //userId 登录id   comment。评价   end 结束周期   status  。。是否办结
        String s = taskMainService.updateBackNew(backNewFilter);
        if ("200".equals(s)) {
            return coverMessage("200", "success");
        } else {
            return coverMessage("500", "失败");
        }
    }


    /**
     * 当前单位用户
     *
     * @param dataBean
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/deptUsers")
    public Message deptUsers(@RequestBody SysUserDataBean dataBean) {
        String deptId = dataBean.getDeptId();
        List<SysUserDataBean> dataBeanList = sysLoginService.getByDeptId(deptId);
        if (ObjectUtils.isNotBlank(dataBeanList)) {
            return coverMessage("200", "单位用户列表", dataBeanList);
        } else {
            return coverMessage("500", "error");
        }
    }

    /**
     * 当前事项匹配了哪些用户
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/categoryInfo", method = RequestMethod.POST)
    public Message categoryInfo(@RequestBody TaskCategoryFilter filter) {
        try {
            TaskCategory category = taskCategoryService.getById(filter.getSysId());
            SysUserDataBean dataBean = sysUserService.getUserDataBeanById(filter.getUserId());
            List<SysUserDataBean> dataBeanList = sysLoginService.getByDeptId(dataBean.getDeptId());
            for (SysUserDataBean userDataBean : dataBeanList) {
                if (StringUtils.isNotBlank(userDataBean.getFloorId())) {
                    if (userDataBean.getFloorId().contains(category.getSysId())) {
                        userDataBean.setImage("1");
                    } else {
                        userDataBean.setImage("0");
                    }
                } else {
                    userDataBean.setImage("0");
                }
            }
            return coverMessage("200", "200", dataBeanList);
        } catch (Exception e) {
            e.printStackTrace();
            return coverMessage("500", "error");
        }
    }

    /**
     * 当前用户匹配了哪些事项
     *
     * @param dataBean
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/userCategory", method = RequestMethod.POST)
    public Message userCategory(@RequestBody SysUserDataBean dataBean) {
        try {
            SysUserDataBean userDataBean = sysUserService.getUserDataBeanById(dataBean.getSysId());
            List<TaskCategory> categories = taskCategoryService.queryFilter(new TaskCategoryFilter());

            for (TaskCategory category : categories) {
                if (StringUtils.isNotBlank(userDataBean.getFloorId())) {
                    if (userDataBean.getFloorId().contains(category.getSysId())) {
                        category.setState("1");
                    } else {
                        category.setState("0");
                    }
                } else {
                    category.setState("0");
                }
            }
            return coverMessage("200", "200", categories);
        } catch (Exception e) {
            e.printStackTrace();
            return coverMessage("500", "error");
        }
    }

    /**
     * 设置该事项类型的人员    (从事项类型分配单位人员)
     *
     * @param
     * @return
     */


    @ResponseBody
    @RequestMapping(value = "/setCategoryUser", method = RequestMethod.POST)
    public Message setCategoryUser(@RequestBody TaskCategoryFilter filter) {
        try {
            String sysId = filter.getSysId();
            String userIds = filter.getUserIds();
//            JSONObject jsonObject = JSONObject.parseObject(userIds);
            List<SysUserDataBean> list = JSONObject.parseArray(userIds, SysUserDataBean.class);
            for (SysUserDataBean userDataBean : list) {
                SysUser user = sysUserService.getById(userDataBean.getUserId());
                String floorId = user.getFloorId();
                if ("1".equals(userDataBean.getImage())) {
                    if (StringUtils.isNotBlank(floorId)) {
                        if (!floorId.contains(sysId)) {
                            floorId = floorId + sysId + ",";
                        }
                    } else {
                        floorId = sysId + ",";
                    }
                } else {
                    if (StringUtils.isNotBlank(floorId)) {
                        if (floorId.contains(sysId)) {
                            floorId = floorId.replace(sysId + ",", "");
                            floorId = floorId.replace("null", "");
                        }
                    }
                }
                user.setFloorId(floorId);
                sysUserService.update(user);
            }
            return coverMessage("200", "成功");
        } catch (Exception e) {
            e.printStackTrace();
            return coverMessage("500", "失败");
        }
    }

    /**
     * 设置督查人员的事项类型   (从人员分配事项类型)
     *
     * @param dataBean
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/setUserCategory", method = RequestMethod.POST)
    public Message setUserCategory(@RequestBody SysUserDataBean dataBean) {
        try {
            SysUser user = sysUserService.getById(dataBean.getUserId());
            //设置该用户的事项类型
            user.setFloorId(dataBean.getFloorId());
            sysUserService.update(user);
            return coverMessage("200", "成功");
        } catch (Exception e) {
            e.printStackTrace();
            return coverMessage("500", "失败");
        }
    }

    /**
     * 任务统计(各任务事项类型具体有多少
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/taskStatistics", method = RequestMethod.POST)
    public Message taskStatistics(@RequestBody SysUserDataBean dataBean) {
        try {
            int all = 0;
            int done = 0;
            int overdue = 0;
            int back = 0;
            String userId = dataBean.getUserId();

            SysUserDataBean user = sysUserService.getUserDataBeanById(userId);
            List<TaskCategory> categories = categoryService.query();
            List<Map<String, Object>> mapList = new ArrayList<>();
            TaskMainFilter taskMainFilter = new TaskMainFilter();
            if (StringUtils.isNotBlank(dataBean.getTime())) {
                //筛选时间
                taskMainFilter.setTime(dataBean.getTime());
            }
            if ("02".equals(user.getRoleId())) {
                //主要领导,统计查看该单位所以的事项类型的个数
                for (TaskCategory category : categories) {

                    taskMainFilter.setInspectionId(user.getDeptId());
                    taskMainFilter.setCategoryId(category.getSysId());
                    all = 0;
                    done = 0;
                    overdue = 0;
                    back = 0;
                    List<TaskMain> taskMainList = taskMainService.queryFilter(taskMainFilter);
                    for (TaskMain taskMain : taskMainList) {
                        List<TaskUnit> taskUnits = taskUnitService.getByMainId(taskMain.getSysId());
                        for (TaskUnit taskUnit : taskUnits) {
                            all++;
                            if ("4".equals(taskUnit.getType())) {
                                done++;
                            }
                            if (StringUtils.isNotBlank(taskUnit.getOverdueDay())) {
                                overdue++;
                            }
                            if (StringUtils.isNotBlank(taskUnit.getBackNum())) {
                                back++;
                            }
                        }
                    }
                    Map<String, Object> map = new HashMap<>();
                    map.put("name", category.getCategory());
                    map.put("value", taskMainList.size());
                    map.put("all", all);
                    map.put("done", done);
                    map.put("overdue", overdue);
                    map.put("back", back);
                    map.put("categoryId", category.getSysId());
                    mapList.add(map);
                }
            } else {
                //非主要领导
                String floorId = user.getFloorId();
                if (StringUtils.isBlank(floorId)) {
                    for (TaskCategory category : categories) {
                        all = 0;
                        done = 0;
                        overdue = 0;
                        back = 0;
                        taskMainFilter.setCreateUser(user.getSysId());
                        taskMainFilter.setCategoryId(category.getSysId());
                        List<TaskMain> taskMainList = taskMainService.queryFilter(taskMainFilter);
                        for (TaskMain taskMain : taskMainList) {
                            List<TaskUnit> taskUnits = taskUnitService.getByMainId(taskMain.getSysId());
                            for (TaskUnit taskUnit : taskUnits) {
                                all++;
                                if ("4".equals(taskUnit.getType())) {
                                    done++;
                                }
                                if (StringUtils.isNotBlank(taskUnit.getOverdueDay())) {
                                    overdue++;
                                }
                                if (StringUtils.isNotBlank(taskUnit.getBackNum())) {
                                    back++;
                                }
                            }
                        }
                        Map<String, Object> map = new HashMap<>();
                        map.put("name", category.getCategory());
                        map.put("value", taskMainList.size());
                        map.put("all", all);
                        map.put("done", done);
                        map.put("overdue", overdue);
                        map.put("back", back);
                        mapList.add(map);
                    }
                } else {
                    String[] split = floorId.split(",");
                    for (String s : split) {
                        TaskCategory taskCategory = categoryService.getById(s);
                        String category = taskCategory.getCategory();
                        taskMainFilter.setCreateUser(user.getSysId());
                        taskMainFilter.setCategoryId(s);
                        List<TaskMain> taskMainList = taskMainService.queryFilter(taskMainFilter);
                        all = 0;
                        done = 0;
                        overdue = 0;
                        back = 0;
                        for (TaskMain taskMain : taskMainList) {
                            List<TaskUnit> taskUnits = taskUnitService.getByMainId(taskMain.getSysId());
                            for (TaskUnit taskUnit : taskUnits) {
                                all++;
                                if ("4".equals(taskUnit.getType())) {
                                    done++;
                                }
                                if (StringUtils.isNotBlank(taskUnit.getOverdueDay())) {
                                    overdue++;
                                }
                                if (StringUtils.isNotBlank(taskUnit.getBackNum())) {
                                    back++;
                                }
                            }
                        }
                        Map<String, Object> map = new HashMap<>();
                        map.put("name", category);
                        map.put("value", taskMainList.size());
                        map.put("all", all);
                        map.put("done", done);
                        map.put("overdue", overdue);
                        map.put("back", back);
                        map.put("categoryId", taskCategory.getSysId());
                        mapList.add(map);
                    }
                }
            }
            return coverMessage("200", "统计汇总", mapList);
        } catch (Exception e) {
            e.printStackTrace();
            return coverMessage("500", "error");
        }
    }

    /**
     * 查询该事项类型下的任务状态统计
     *
     * @param
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryCategoryId", method = RequestMethod.POST)
    public Message queryCategoryNum(@RequestBody TaskMainFilter filter) {
        try {
            SysUserDataBean user = sysUserService.getUserDataBeanById(filter.getUserId());
            filter.setUserId(null);
            if ("02".equals(user.getRoleId())) {
                filter.setInspectionId(user.getDeptId());
            } else {
                filter.setCreateUser(user.getUserId());
            }
            filter.setCategoryId(filter.getCategoryId());
            List<TaskMain> taskMainList = taskMainService.queryFilter(filter);
            int daiqianshou = 0;
            int daifankui = 0;
            int yifankui = 0;
            int tuihuichongban = 0;
            int yiwancheng = 0;
            int yiqianshou = 0;
            List<SysUserDataBean> userList = new ArrayList<>();
            for (TaskMain taskMain : taskMainList) {
                List<CopeTo> copeTos = copeToService.getByTaskMainId(taskMain.getSysId());
                if (ObjectUtils.isNotBlank(copeTos)) {
                    //去重
                    copeTos = copeTos.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(CopeTo::getTaskMainId))), ArrayList::new));
                    for (CopeTo copeTo : copeTos) {
                        /*
                        for (Iterator<CopeTo> i = copeTos.iterator(); i.hasNext(); ) {
                            CopeTo o = i.next();
                            if (o.getTaskMainId().equals(copeTo.getTaskMainId())) {
                                i.remove();
                            }
                        }*/
                        SysUserDataBean userDataBean = sysUserService.getUserDataBeanById(copeTo.getLeaderId());
                        userDataBean.setI(1);
                        userList.add(userDataBean);
                    }
                }
                List<TaskUnit> taskUnits = taskUnitService.getByMainId(taskMain.getSysId());
                for (TaskUnit taskUnit : taskUnits) {
                    if ("0".equals(taskUnit.getType())) {
                        //待签收
                        daiqianshou++;
                    } else if ("1".equals(taskUnit.getType())) {
                        //待反馈
                        daifankui++;
                    } else if ("2".equals(taskUnit.getType())) {
                        //yifankui
                        yifankui++;
                    } else if ("3".equals(taskUnit.getType())) {
                        //tuihuichongban
                        tuihuichongban++;
                    } else if ("4".equals(taskUnit.getType())) {
                        //yiwancheng
                        yiwancheng++;
                    } else if ("5".equals(taskUnit.getType())) {
                        //yiqianshou
                        yiqianshou++;
                    }
                }
            }
            Map<String, Object> leaderMap = new HashMap<>();
            if (ObjectUtils.isNotBlank(userList)) {
                for (SysUserDataBean userDataBean : userList) {
                    String username = userDataBean.getUsername();
                    leaderMap.put(username, leaderMap.get(username) == null ? userDataBean.getI() : ((Integer) leaderMap.get(userDataBean.getUsername()) + userDataBean.getI()));
                }
            }
            List<Map<String, Object>> leaderList = new ArrayList<>();
            for (String key : leaderMap.keySet()) {
                HashMap<String, Object> hashMap = new HashMap<>();
                int o = (int) leaderMap.get(key);
                hashMap.put("name", key);
                hashMap.put("num", o);
                leaderList.add(hashMap);
            }
            Map<String, Object> map = new HashMap<>();
            map.put("daiqianshou", daiqianshou);
            map.put("daifankui", daifankui);
            map.put("yifankui", yifankui);
            map.put("tuihuichongban", tuihuichongban);
            map.put("yiwancheng", yiwancheng);
            map.put("yiqianshou", yiqianshou);
            map.put("leaderList", leaderList);
            return coverMessage("200", "事项统计详情", map);
        } catch (Exception e) {
            e.printStackTrace();
            return coverMessage("500", "error");
        }
    }

    /**
     * 事项类型列表
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryCategory", method = RequestMethod.POST)
    public Message queryCategory(@RequestBody TaskCategoryFilter filter) {
        try {
            String userId = filter.getUserId();
            SysUserDataBean sysUserDataBean = sysUserService.getUserDataBeanById(userId);
            List<TaskCategory> list = categoryService.queryFilter(filter);
            return coverMessage("200", "事项类型列表", list);
        } catch (Exception e) {
            e.printStackTrace();
            return coverMessage("500", "error");
        }
    }

    @ResponseBody
    @RequestMapping(value = "/addCategory", method = RequestMethod.POST)
    public Message addCategory(@RequestBody TaskCategory taskCategory) {
        try {
            int i = taskCategoryService.queryMaxIndex();
            i++;
            String index = "";
            if (i < 10) {
                index = "0" + i;
            } else {
                index = i + "";
            }
            taskCategory.setIndexNum(index);
            if (StringUtils.isNotBlank(taskCategory.getCategory())) {
                return coverMessage("500", "请输入事项类型");
            }
            taskCategoryService.save(taskCategory);
            return coverMessage("200", "200");
        } catch (Exception e) {
            e.printStackTrace();
            return coverMessage("500", "500");
        }
    }

    /**
     * 编辑事项类型分类
     *
     * @param
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/editCategory", method = RequestMethod.POST)
    public Message editCategory(@RequestBody TaskCategoryFilter json) {
        try {
            System.out.println(json);
            SysUserDataBean userDataBean = sysUserService.getUserDataBeanById(json.getUserId());
            List<TaskCategory> categories = JSONObject.parseArray(json.getJson(), TaskCategory.class);
           /* String list = jsonObject.getString("list");
            List<TaskCategory> categories = JSONArray.parseArray(list, TaskCategory.class);
         */
            for (TaskCategory category : categories) {
                if (StringUtils.isNotBlank(category.getSysId())) {
                    //修改

                    TaskCategory byId = categoryService.getById(category.getSysId());

                    if (!byId.getCategory().equals(category.getCategory())) {
                        //修改名字
                        if ("会议纪要".equals(category.getCategory()) || "单位重大事项".equals(category.getCategory()) || "书记、县长批示件".equals(category.getCategory())) {
                            continue;
                        }
                        TaskCategoryLog taskCategoryLog = new TaskCategoryLog();
                        taskCategoryLog.setCategoryId(byId.getSysId());
                        taskCategoryLog.setCategoryName(byId.getCategory());// 原名称
                        taskCategoryLog.setDateTime(DateUtils.getDateTime());
                        taskCategoryLog.setIp(json.getIp());
                        taskCategoryLog.setUserId(json.getUserId());
                        taskCategoryLog.setUserName(userDataBean.getUsername());
                        taskCategoryLog.setType("1");//修改
                        taskCategoryLog.setContent("修改事项类型名称");
                        taskCategoryLogService.save(taskCategoryLog);
                    }
                    if (!byId.getType().equals(category.getType())) {
                        //修改名字
                        TaskCategoryLog taskCategoryLog = new TaskCategoryLog();
                        taskCategoryLog.setCategoryId(byId.getSysId());
                        taskCategoryLog.setCategoryName(byId.getCategory());// 名称
                        taskCategoryLog.setOther(byId.getType());// 原分数
                        taskCategoryLog.setDateTime(DateUtils.getDateTime());
                        taskCategoryLog.setIp(json.getIp());
                        taskCategoryLog.setUserName(userDataBean.getUsername());

                        taskCategoryLog.setType("1");//修改
                        taskCategoryLog.setUserId(json.getUserId());
                        taskCategoryLog.setContent("修改事项类型名分数");
                        taskCategoryLogService.save(taskCategoryLog);
                    }
                    category.setUpdUser(json.getUserId());
                    taskCategoryService.update(category);
                } else {
                    //新增
                    category.setCreateUser(json.getUserId());
                    taskCategoryService.save(category);
                    TaskCategoryLog taskCategoryLog = new TaskCategoryLog();
                    taskCategoryLog.setCategoryName(category.getCategory());// 名称
                    taskCategoryLog.setOther(category.getType());// 原分数
                    taskCategoryLog.setDateTime(DateUtils.getDateTime());
                    taskCategoryLog.setIp(json.getIp());
                    taskCategoryLog.setUserName(userDataBean.getUserId());

                    taskCategoryLog.setType("2");//新增
                    taskCategoryLog.setUserId(json.getUserId());
                    taskCategoryLog.setContent("新增事项类型");
                    taskCategoryLogService.save(taskCategoryLog);
                }
            }
            return coverMessage("200", "更新成功");
        } catch (BeansException e) {
            e.printStackTrace();
            return coverMessage("500", "error");
        }
    }

    @ResponseBody
    @RequestMapping(value = "/delCategory", method = RequestMethod.POST)
    public Message delCategory(@RequestBody TaskCategoryFilter filter) {
        String sysId = filter.getSysId();
        TaskCategory category = taskCategoryService.getById(sysId);
        TaskMainFilter taskMainFilter = new TaskMainFilter();
        taskMainFilter.setCategoryId(sysId);
        List<TaskMain> taskMainList = taskMainService.queryFilter(taskMainFilter);
        if (ObjectUtils.isNotBlank(taskMainList)) {
            return coverMessage("500", "该事项类型有任务存在");
        } else {
            if ("会议纪要".equals(category.getCategory()) || "单位重大事项".equals(category.getCategory()) || "书记、县长批示件".equals(category.getCategory())) {
                return coverMessage("500", "该事项类型无法删除");
            }
            taskCategoryService.deleteById(sysId);
            TaskCategoryLog taskCategoryLog = new TaskCategoryLog();
            taskCategoryLog.setCategoryName(category.getCategory());// 名称
            taskCategoryLog.setOther(category.getType());// 原分数
            taskCategoryLog.setDateTime(DateUtils.getDateTime());
            taskCategoryLog.setIp(filter.getIp());
            taskCategoryLog.setType("0");//新增
            taskCategoryLog.setUserId(filter.getUserId());
            taskCategoryLog.setContent("删除事项类型");
            taskCategoryLogService.save(taskCategoryLog);
            return coverMessage("200", "删除成功");
        }
    }

    /**
     * 反馈汇总任务列表
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/collectTaskList", method = RequestMethod.POST)
    public Message collectTaskList(@RequestBody TaskUnitFilter filter) {
        try {
            String userId = filter.getUserId();
            List<TaskUnit> unitList = new ArrayList<>();
            SysUserDataBean user = sysUserService.getUserDataBeanById(userId);
            TaskMainFilter taskMainFilter = new TaskMainFilter();
            if ("02".equals(user.getRoleId())) {
                taskMainFilter.setInspectionId(user.getDeptId());
            } else {
                taskMainFilter.setCreateUser(user.getUserId());
            }
            taskMainFilter.setCategoryId(filter.getCategoryId());
            List<TaskMain> taskMainList = taskMainService.queryFilter(taskMainFilter);
            if (ObjectUtils.isNotBlank(taskMainList)) {
                for (TaskMain taskMain : taskMainList) {
                    List<TaskUnit> taskUnits = taskUnitService.getByMainId(taskMain.getSysId());
                    for (TaskUnit taskUnit : taskUnits) {
                        if ("4".equals(taskUnit.getType())) {
                            unitList.add(taskUnit);
                        }
                    }
                }
                return coverMessage("200", "已完成单位任务", unitList);
            } else {
                return coverMessage("500", "无数据");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return coverMessage("500", "error");
        }
    }

    /**
     * 反馈汇总二级反馈列表页
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/collect2", method = RequestMethod.POST)
    public Message collect2(@RequestBody TaskUnitFilter filter) {
        try {
            //当前单位任务
            TaskUnit taskUnit = taskUnitService.getById(filter.getSysId());
            //根据当前任务的子任务id和接收人id查询反馈信息
            List<TaskBackNewBean> taskBackNewBeanList = new ArrayList<>();
            List<TaskBackNew> taskBackNews = taskBackNewService.getByRecipientIdAndSubId(filter.getUserId(), taskUnit.getTaskSubId());
            TaskBackNewBean taskBackNewBean = new TaskBackNewBean();
            for (TaskBackNew taskBackNew : taskBackNews) {
                BeanUtils.copyProperties(taskBackNew, taskBackNewBean);
                String[] file = splitString(taskBackNew.getFile());
                String[] fileName = splitString(taskBackNew.getFileName());
                List<Map<String, Object>> backFileList = new ArrayList<>();
                if (ObjectUtils.isNotBlank(file)) {
                    for (int i = 0; i < file.length; i++) {
                        Map<String, Object> map = new HashMap<>();
                        map.put("file", file[i]);
                        map.put("fileName", fileName[i]);
                        backFileList.add(map);
                    }
                }
                taskBackNewBean.setFiles(backFileList);
                taskBackNewBeanList.add(taskBackNewBean);
            }
            //当前汇总的子任务
            TaskSub taskSub = taskSubService.getById(taskUnit.getTaskSubId());
            TaskSubBean taskSubBean = new TaskSubBean();
            BeanUtils.copyProperties(taskSub, taskSubBean);
            String[] files = splitString(taskSub.getSubSituationFile());
            String[] fileNames = splitString(taskSub.getFileName());
            List<Map<String, Object>> fileMapList = new ArrayList<>();
            if (ObjectUtils.isNotBlank(files)) {
                for (int i = 0; i < files.length; i++) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("file", files[i]);
                    map.put("fileName", fileNames[i]);
                    fileMapList.add(map);
                }
                taskSubBean.setSubSituationFile(fileMapList);
            }
            Map<String, Object> map = new HashMap<>();
            map.put("taskSub", taskSubBean);
            map.put("taskBackNews", taskBackNewBeanList);
            return coverMessage("200", "汇总二级数据", map);
        } catch (BeansException e) {
            e.printStackTrace();
            return coverMessage("500", "error");
        }
    }

    /**
     * 保存汇总信息
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/editCollect", method = RequestMethod.POST)
    public Message editCollect(@RequestBody TaskSubFilter filter) {
        try {
            TaskSub taskSub = taskSubService.getById(filter.getSysId());
            taskSub.setSubSituation(filter.getSubSituation());
            taskSub.setSubProblem(filter.getSubProblem());
            taskSub.setSubPlan(filter.getSubPlan());
            taskSubService.update(taskSub);
            return coverMessage("200", "保存成功");
        } catch (Exception e) {
            e.printStackTrace();
            return coverMessage("500", "error");
        }
    }

    /**
     * 返回修改任务页面
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/MainDetail", method = RequestMethod.POST)
    public Message MainDetail(@RequestBody TaskMainFilter filter) {
        TaskMain taskMain = taskMainService.getById(filter.getSysId());
        TaskMainBean taskMainBean = new TaskMainBean();

        BeanUtils.copyProperties(taskMain, taskMainBean);
        String[] files = splitString(taskMain.getFile());
        String[] fileNames = splitString(taskMain.getFileName());
        List<Map<String, Object>> fileMapList = new ArrayList<>();

        if (ObjectUtils.isNotBlank(files)) {
            for (int i = 0; i < files.length; i++) {
                Map<String, Object> map = new HashMap<>();
                map.put("file", files[i]);
                map.put("fileName", fileNames[i]);
                fileMapList.add(map);
            }
            taskMainBean.setFiles(fileMapList);
        }
        TaskSubFilter taskSubFilter = new TaskSubFilter();
        taskSubFilter.setTaskMainId(filter.getSysId());
        List<TaskCategory> taskCategories = taskCategoryService.query();
        List<TaskSub> taskSubList = taskSubService.queryFilter(taskSubFilter);
        List<TaskSubFilter> subFilterList = new ArrayList<>();
        for (TaskSub taskSub : taskSubList) {
            TaskSubFilter subFilter = new TaskSubFilter();
            BeanUtils.copyProperties(taskSub, subFilter);
            List<TaskUnit> unitList = taskUnitService.getBySubId(taskSub.getSysId());
            subFilter.setTaskUnitList(unitList);
            subFilterList.add(subFilter);
        }
        if (ObjectUtils.isNotBlank(taskMainBean)) {
            Map map = new HashMap<String, Object>();
            map.put("taskMain", taskMainBean);
            map.put("taskCategories", taskCategories);
            return coverMessage("200", "200", map);
        } else {
            return coverMessage("500", "error");
        }
    }

    /**
     * 保存修改的主任务
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateMain", method = RequestMethod.POST)
    public Message updateMain(@RequestBody TaskMainFilter filter) {
        String result = taskMainService.updateTaskMain(filter);
        if ("200".equals(result)) {
            return coverMessage("200", "修改成功");
        } else {
            return coverMessage("500", "修改失败");
        }
    }

    /**
     * 保存新增的子任务
     *
     * @return
     */

    @ResponseBody
    @RequestMapping(value = "/addTaskSub", method = RequestMethod.POST)
    public Message addTaskSub(@RequestBody TaskSubFilter filter) {
        String result = null;
        try {
            result = taskMainService.addTaskSub(filter);
        } catch (Exception e) {
            e.printStackTrace();
            return coverMessage("500", result + e.getMessage());
        }
        if ("200".equals(result)) {
            return coverMessage("200", result);
        } else {
            return coverMessage("500", result);
        }
    }

    /**
     * 排除当前子任务已有单位
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/subDeptList")
    public Message subDeptList(@RequestBody TaskUnitFilter filter) {
        try {
            List<SysDept> sysDeptList = deptService.queryByDeptLevel(3);
            List<TaskUnit> taskUnits = taskUnitService.getBySubId(filter.getTaskSubId());
            for (TaskUnit taskUnit : taskUnits) {
                SysDept taskDept = deptService.getById(taskUnit.getDeptId());
                if (StringUtils.isNotBlank(taskDept.getSysId())) {
                    //去重
                    for (Iterator<SysDept> i = sysDeptList.iterator(); i.hasNext(); ) {
                        SysDept o = i.next();
                        if (o.getSysId().equals(taskDept.getSysId())) {
                            i.remove();
                        }
                    }
                }
            }
            return coverMessage("200", "单位", sysDeptList);
        } catch (Exception e) {
            e.printStackTrace();
            return coverMessage("500", e.getMessage());
        }
    }

    /**
     * 子任务添加单位
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/addTaskUnit", method = RequestMethod.POST)
    public Message addTaskUnit(@RequestBody TaskSubFilter filter) {
        String result = "";
        try {
            result = taskMainService.addTaskUnit(filter);
        } catch (ParseException e) {
            e.printStackTrace();
            return coverMessage("500", e.getMessage());
        }
        if ("200".equals(result)) {
            return coverMessage("200", "保存成功");
        } else {
            return coverMessage("500", result);
        }
    }

    /**
     * 删除任务（逻辑删除，改变任务状态）
     *
     * @param
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/delTaskMain", method = RequestMethod.POST)
    public Message delete(@RequestBody TaskMainFilter filter) {
        String sysId = filter.getSysId();
        ArrayList<String> ids = new ArrayList<>();
        ids.add(sysId);
        String result = taskMainService.updateDel(ids, filter.getUserId(), filter.getOther());
        if ("200".equals(result)) {
            return coverMessage("200", "删除成功");
        } else {
            return coverMessage("500", "error");
        }
    }

    /**
     * 删除单位任务
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/delTaskUnit")
    public Message deleteUnit(@RequestBody TaskUnitFilter filter) {
        String result = taskMainService.updateDelUnit(filter.getSysId());
        if ("200".equals(result)) {
            return coverMessage("200", "删除成功");
        } else {
            return coverMessage("500", "删除失败");
        }
    }
}